<template>
  <div class="container">
    <div class="title">
      <span>明细账</span>
      <el-date-picker
        v-model="monthRange"
        type="monthrange"
        range-separator="至"
        start-placeholder="开始月份"
        end-placeholder="结束月份"
        value-format="YYYY-MM"
        @change="handleMonthChange"
      >
      </el-date-picker>
    </div>
    <div v-for="item in monthEve" :key="item.keyMonth">
      <span class="tableTitle">{{ item.keyMonth }}</span>
      <el-table
        :data="item.keyData"
        row-key="detaild_id"
        width="100%"
        border
        stripe
      >
        <el-table-column
          prop="account_code"
          label="科目代码"
          max-width="170"
          align="center"
        />
        <el-table-column
          prop="account_name"
          label="科目名称"
          align="center"
          max-width="170"
        />
        <el-table-column
          prop="period"
          label="日期"
          max-width="170"
          align="center"
        />
        <el-table-column
          prop="voucher_number"
          label="凭证号"
          max-width="170"
          align="center"
        >
          <template #default="scope">
            <el-button
              type="text"
              size="small"
              @click="handleEdit(scope.$index, scope.row)"
            >
              {{ scope.row.voucher_number }}
            </el-button>
          </template>
        </el-table-column>
        <el-table-column
          prop="summary"
          label="摘要"
          max-width="170"
          align="center"
        />
        <el-table-column
          prop="debit_amount"
          label="借方"
          max-width="170"
          align="center"
        />
        <el-table-column
          prop="credit_amount"
          label="贷方"
          max-width="170"
          align="center"
        />
        <el-table-column
          prop="direction"
          label="方向"
          max-width="170"
          align="center"
        />
        <el-table-column
          prop="balance"
          label="余额"
          max-width="170"
          align="center"
        />
      </el-table>
    </div>
    <div
      v-if="loading"
      style="margin-top: 3vh"
      v-loading="loading"
      element-loading-text="加载中..."
      element-loading-spinner=""
    ></div>
    <div :ref="(el) => observerTargets.push(el)" style="height: 1px"></div>
    <div class="abow_dialog">
      <el-dialog v-model="dialogVisible" width="80%">
        <iframe
          id="myIframe"
          :src="iframeSrc"
          width="100%"
          height="800vh"
        ></iframe>
      </el-dialog>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, nextTick } from "vue";
import { getDetailList, getPdf } from "@/api/getList";
import { ElMessage } from "element-plus";
import { Loading } from "@element-plus/icons";

// 响应式变量
const observerTargets = ref([]);
const currentMonth = ref(null);
const page = ref("");
const monthRange = ref([]);
const tempArr = ref([]);
const monthEve = ref([]);
const iframeSrc = ref("");
const dialogVisible = ref(false);
const loading = ref(false);

// 从历史状态获取月份范围
monthRange.value[0] = history.state?.startMonth;
monthRange.value[1] = history.state?.endMonth;

// 计算日期范围的函数
const calculateDateRange = (startMonth, monthRange) => {
  const startYear = startMonth.getFullYear();
  const startMonthStr = String(startMonth.getMonth() + 1).padStart(2, "0");
  // 修改为往后推一个月
  const endMonth = new Date(startYear, startMonth.getMonth() + 1);
  let endYear = endMonth.getFullYear();
  let endMonthStr = String(endMonth.getMonth() + 1).padStart(2, "0");
  const finalEndMonth = new Date(monthRange[1]);
  const finalEndYear = finalEndMonth.getFullYear();
  const finalEndMonthStr = String(finalEndMonth.getMonth() + 1).padStart(
    2,
    "0"
  );
  if (`${endYear}-${endMonthStr}` > `${finalEndYear}-${finalEndMonthStr}`) {
    endMonth.setFullYear(finalEndYear);
    endMonth.setMonth(finalEndMonth.getMonth());
    endYear = endMonth.getFullYear();
    endMonthStr = String(endMonth.getMonth() + 1).padStart(2, "0");
  }
  return {
    start: `${startYear}-${startMonthStr}`,
    end: `${endYear}-${endMonthStr}`,
  };
};

// 处理月份变化
const handleMonthChange = (value) => {
  if (value && value.length === 2) {
    const startMonth = new Date(value[0]);
    currentMonth.value = startMonth;
    const { start, end } = calculateDateRange(startMonth, monthRange.value);
    fetchDataByMonth(start, end);
  }
};

// 交集观察器
const observer = new IntersectionObserver((entries) => {
  if (entries[0].isIntersecting && currentMonth.value) {
    currentMonth.value.setMonth(currentMonth.value.getMonth() + 1);
    const { start, end } = calculateDateRange(
      currentMonth.value,
      monthRange.value
    );
    if (start <= monthRange.value[1]) {
      fetchDataByMonth(start, end);
    }
  }
});

// 按月份获取数据
const fetchDataByMonth = async (startMonth, endMonth) => {
  try {
    loading.value = true;
    const res = await getDetailList({
      start_month: startMonth,
      end_month: endMonth,
    });
    tempArr.value = [];
    if (Object.keys(res.data).length === 0) {
      loading.value = false;
      ElMessage.error("文件不存在，请上传！");
    } else {
      for (const key in res.data) {
        res.data[key].forEach((e, index) => {
          if (!e.detaild_id) {
            e.children = [];
            e.detaild_id = index;
            tempArr.value.push(e);
          }
        });
        tempArr.value.forEach((i) => {
          res.data[key].forEach((j) => {
            if (
              i.account_code === Number(String(j.account_code).slice(0, 4)) &&
              j.direction
            ) {
              i.children.push(j);
            }
          });
        });
        res.data[key] = tempArr.value;
        const existingIndex = monthEve.value.findIndex(
          (item) => item.keyMonth === key
        );
        if (existingIndex > -1) {
          monthEve.value[existingIndex].keyData = [
            ...monthEve.value[existingIndex].keyData,
            ...res.data[key],
          ];
        } else {
          monthEve.value.push({
            keyMonth: key,
            keyData: res.data[key],
          });
          loading.value = false;
        }
      }
      nextTick(() => {
        if (observerTargets.value.length > 0) {
          const lastTarget =
            observerTargets.value[observerTargets.value.length - 1];
          observer.observe(lastTarget);
        } else {
          console.error("仍然未获取到 observerTarget 元素");
        }
      });
    }
  } catch (error) {
    console.error("请求出错:", error);
  }
};

// 处理编辑操作
const handleEdit = (a, b) => {
  page.value = b.voucher_paging?.split(",")[0];
  const data = {
    file_type: 6,
    file_month: b.period.slice(0, 7),
  };
  getPdf(data)
    .then((res) => {
      if (!res || !res.data || !res.data.url) {
        ElMessage.error("缺少凭证，请上传！");
        return;
      }
      iframeSrc.value = `../src/static/pdfjs/web/viewer.html?file=${res.data.url}#page=${page.value}`;
      dialogVisible.value = true;
    })
    .catch((error) => {
      console.error("获取 PDF 信息出错:", error);
      ElMessage.error("获取 PDF 信息出错，请稍后重试");
    });
};

// 组件挂载时初始化数据
onMounted(() => {
  if (monthRange.value[0] && monthRange.value[1]) {
    const startMonth = new Date(monthRange.value[0]);
    currentMonth.value = startMonth;
    const { start, end } = calculateDateRange(startMonth, monthRange.value);
    fetchDataByMonth(start, end);
  }
});
</script>

<style lang="less" scoped>
.container {
  height: calc(100vh - 142px);
  background: @mainColor;

  .title {
    display: flex;
    flex-direction: row;
    flex-wrap: nowrap;
    align-items: center;
  }
  span {
    margin: 1vw;
  }
}
.tableTitle {
  margin: 1vh;
  font-size: 1.2vw;
}
.abow_dialog {
  display: flex;
  justify-content: center;
  align-items: Center;
  overflow: hidden;
}
:deep(.abow_dialog) {
  .el-dialog {
    margin-top: 6vh;
    height: 90%;
    overflow: hidden;
    .el-dialog__body {
      position: absolute;
      left: 0;
      top: 54px;
      bottom: 0;
      right: 0;
      padding: 0;
      z-index: 1;
      overflow: hidden;
      overflow-y: auto;
    }
  }
}
.tableTitle {
  display: inline-block;
  margin: 1vh;
  font-size: 1.2vw;
}
/* 隐藏当前组件内 el-loading 的转圈图标 */
:deep(.el-loading-spinner .circular) {
  display: none;
}

.table-loading {
  text-align: center;
  padding: 20px;
}
:deep(.title) {
  width: 25vw;
}
</style>
